package com.mox.enterprise.util;


import com.mox.enterprise.constants.CommonConstants;
import com.mox.enterprise.constants.Url;
import com.mox.enterprise.factory.Factory;
import com.mox.enterprise.service.RemoteService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * 创建时间： 2018/8/3 15:44
 * 描述：    网络请求的封装
 *
 * @author mox
 */
@SuppressWarnings("unused")
public class Network {

    private static Network instance;
    private Retrofit retrofit;
    private OkHttpClient client;

    static {
        instance = new Network();
    }

    private Network() {
    }

    private static OkHttpClient getClient() {
        if (instance.client != null) {
            return instance.client;
        }

        //获取一个client
        instance.client = new OkHttpClient
                .Builder()
                .readTimeout(CommonConstants.DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .writeTimeout(CommonConstants.DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .connectTimeout(CommonConstants.DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                //添加一个拦截器
                .addInterceptor(chain -> {
                    Request original = chain.request();
                    Request.Builder builder = original.newBuilder();
                    //添加一个请求头
                    //  builder.addHeader(CommonConstants.CONTENT_TYPE, CommonConstants.CONTENT_TYPE_VALUE);
                    builder.addHeader(CommonConstants.USER_AGENT, CommonConstants.USER_AGENT_VALUE);
                    builder.addHeader(CommonConstants.CONTENT_TYPE, CommonConstants.CONTENT_TYPE_VALUE);

                    return chain.proceed(builder.build());
                })
                .build();
        //存储client
        return instance.client;
    }

    /**
     * @return Retrofit
     */
    private static Retrofit getRetrofit() {
        if (instance.retrofit != null) {
            return instance.retrofit;
        }
        //获取一个client
        OkHttpClient client = getClient();

        Retrofit.Builder builder = new Retrofit.Builder();
        instance.retrofit = builder
                .baseUrl(Url.BASE_URL)
                .client(client)
                //设置gson解析器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(Factory.getGson()))
                .build();
        return instance.retrofit;
    }

    /**
     * 得到一个请求代理
     *
     * @return RemoteService
     */
    public static RemoteService remoteService() {
        return Network.getRetrofit().create(RemoteService.class);
    }
}
